package com.dupt.web.controller.material;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import com.dupt.common.utils.DateUtils;
import com.dupt.common.utils.DictUtils;
import com.dupt.common.utils.SecurityUtils;
import com.dupt.system.domain.MaterialSerial;
import com.dupt.system.domain.param.MaterialBorrowReturnParam;
import com.dupt.system.domain.vo.MaterialBorrowReturnVo;
import com.dupt.system.service.IMaterialDetialService;
import com.dupt.system.service.IMaterialSerialService;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.dupt.common.annotation.Log;
import com.dupt.common.core.controller.BaseController;
import com.dupt.common.core.domain.AjaxResult;
import com.dupt.common.enums.BusinessType;
import com.dupt.system.domain.MaterialBorrowReturn;
import com.dupt.system.service.IMaterialBorrowReturnService;
import com.dupt.common.utils.poi.ExcelUtil;
import com.dupt.common.core.page.TableDataInfo;

/**
 * 借用归还信息Controller
 * 
 * @author zhuanyusun
 * @date 2025-06-09
 */
@RestController
@RequestMapping("/material/return")
public class MaterialBorrowReturnController extends BaseController
{
    @Autowired
    private IMaterialBorrowReturnService materialBorrowReturnService;
    @Autowired
    private IMaterialDetialService materialDetialService;
    @Autowired
    private IMaterialSerialService materialSerialService;

    /**
     * 查询借用归还信息列表
     */
    @PreAuthorize("@ss.hasPermi('material:return:list')")
    @GetMapping("/list")
    public TableDataInfo list(MaterialBorrowReturnParam materialBorrowReturnParam)
    {
        startPage();
        List<MaterialBorrowReturnVo> list = materialBorrowReturnService.selectMaterialBorrowReturnList(materialBorrowReturnParam);
        return getDataTable(list);
    }

    /**
     * 导出借用归还信息列表
     */
    @PreAuthorize("@ss.hasPermi('material:return:export')")
    @Log(title = "借用归还信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MaterialBorrowReturnParam materialBorrowReturnParam)
    {
        List<MaterialBorrowReturnVo> list = materialBorrowReturnService.selectMaterialBorrowReturnList(materialBorrowReturnParam);
        ExcelUtil<MaterialBorrowReturnVo> util = new ExcelUtil<MaterialBorrowReturnVo>(MaterialBorrowReturnVo.class);
        util.exportExcel(response, list, "借用归还信息数据");
    }

    /**
     * 获取借用归还信息详细信息(归还)
     */
    @PreAuthorize("@ss.hasPermi('material:return:query')")
    @GetMapping(value = "/{materialBorrowId}")
    public AjaxResult getInfo(@PathVariable("materialBorrowId") Long materialBorrowId)
    {
        //根据借用ID查询借用信息
        MaterialBorrowReturn materialBorrowReturn = materialBorrowReturnService.selectMaterialBorrowReturnByMaterialBorrowId(materialBorrowId);
        if(materialBorrowReturn==null){
            return error("当前借用信息不存在，请联系管理员。");
        }
        materialBorrowReturn.setReturnTime(DateUtils.getNowDate());
        materialBorrowReturn.setIsReturn(1);
        materialBorrowReturn.setUpdateBy(SecurityUtils.getLoginUser().getUsername());
        materialBorrowReturn.setUpdateTime(DateUtils.getNowDate());
        materialBorrowReturnService.updateMaterialBorrowReturn(materialBorrowReturn);
        //修改物料状态信息
        MaterialSerial materialSerial = materialSerialService.selectMaterialSerialByMaterialSerialId(materialBorrowReturn.getMaterialSerialId());
        materialSerial.setStatus(DictUtils.getDictValue("sys_material_status","在库"));
        materialSerial.setCurrentPos(materialSerial.getOriginalPos());
        materialSerial.setUpdateTime(DateUtils.getNowDate());
        materialSerial.setUpdateBy(SecurityUtils.getLoginUser().getUsername());
        materialSerialService.updateMaterialSerial(materialSerial);
        return success("归还成功");
    }

    /**
     * 新增借用归还信息
     */
    @PreAuthorize("@ss.hasPermi('material:return:add')")
    @Log(title = "借用归还信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MaterialBorrowReturnParam materialBorrowReturnParam)
    {
        //根据序列号查询序列号信息
        List<MaterialSerial> serialList = materialSerialService.selectMaterialSerialBySerialNo(materialBorrowReturnParam.getSerialNo());
        //根据物料ID查询物料信息
        //2.保存借用信息
        MaterialBorrowReturn materialBorrowReturn = new MaterialBorrowReturn();
        BeanUtils.copyProperties(materialBorrowReturnParam,materialBorrowReturn);
        materialBorrowReturn.setMaterialSerialId(serialList.get(0).getMaterialSerialId());
        materialBorrowReturn.setBorrowTime(DateUtils.getNowDate());
        materialBorrowReturn.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        materialBorrowReturn.setCreateTime(DateUtils.getNowDate());
        materialBorrowReturnService.insertMaterialBorrowReturn(materialBorrowReturn);
        //3.修改物料状态信息
        MaterialSerial materialSerial = serialList.get(0);
        materialSerial.setStatus(DictUtils.getDictValue("sys_material_status","借用"));
        materialSerial.setCurrentPos(materialBorrowReturnParam.getBorrowBy().split("-")[0]);
        materialSerial.setUpdateTime(DateUtils.getNowDate());
        materialSerial.setUpdateBy(SecurityUtils.getLoginUser().getUsername());
        materialSerialService.updateMaterialSerial(materialSerial);
        return success("借用成功");
    }

    /**
     * 修改借用归还信息
     */
    @PreAuthorize("@ss.hasPermi('material:return:edit')")
    @Log(title = "借用归还信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MaterialBorrowReturn materialBorrowReturn)
    {
        return toAjax(materialBorrowReturnService.updateMaterialBorrowReturn(materialBorrowReturn));
    }

    /**
     * 删除借用归还信息
     */
    @PreAuthorize("@ss.hasPermi('material:return:remove')")
    @Log(title = "借用归还信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{materialBorrowIds}")
    public AjaxResult remove(@PathVariable Long[] materialBorrowIds)
    {
        //根据借用ID查询借用信息
        List<MaterialBorrowReturn> returnList = materialBorrowReturnService.selectMaterialBorrowReturnByMaterialBorrowIds(materialBorrowIds);
        //删除所有的信息
        materialBorrowReturnService.deleteMaterialBorrowReturnByMaterialBorrowIds(materialBorrowIds);
        //获取所有的序列号ID
        List<Long> materialSerialIds = returnList.stream()
                .map(MaterialBorrowReturn::getMaterialSerialId)
                .collect(Collectors.toList());
        //转换为 long[]
        Long[] longArray = materialSerialIds.stream()
                .filter(Objects::nonNull)
                .toArray(Long[]::new);
        List<MaterialSerial> serialList = materialSerialService.selectMaterialSerialByMaterialSerialIds(longArray);
        serialList.forEach(detail -> {
            detail.setStatus(DictUtils.getDictValue("sys_material_status","在库")); // 设置为"在库"
            detail.setCurrentPos(detail.getOriginalPos());
            detail.setUpdateTime(DateUtils.getNowDate());
            detail.setUpdateBy(SecurityUtils.getLoginUser().getUsername());
        });
        materialSerialService.batchUpdateMaterialSerial(serialList);
        return success("删除成功");
    }
}
